<template>
	<om-addpage :menuList='menuList' :showChooseBtn="ismenu"  style="padding-top: 35px;" :checkedit="checkedit" :menuName="menuName" @formSubmit="formSubmit" :busCode="busCode">
		<om-autoform ref="autoform" :checkedit="checkedit" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		getUrl,
		confirmModal,
		errorModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		hasEditor,
		getEditorTitle,
		changeConfigAttr,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import {zposUrl} from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	import moment from '@/static/js/moment.js'
	export default {
		data() {
			return buildFormData({
				communicateUserIdCache:'aft-bx-afterSalesService-communicateUserId-cache',
				serviceUserIdCache:'aft-bx-afterSalesService-serviceUserId-cache',
				checkedit:false,
				feeUserIdCache:'aft-bx-afterSalesService-feeUserId-cache',
				menuList:[],
				ismenu:false
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId','salaryInstId','salaryInstName'])
		},
		provide() {
			return {
				formPage: this
			}
		},
		watch:{	
			'formdata.feeAmount':function(newVal,oldVal){
				let _that = this;
				if(Number(_that.$refs.autoform.formdata.feeAmount) > 0){
					_that.$refs.autoform.changeEditor("title1","feeStatusId","type","selectbox")
				}else{
					_that.$refs.autoform.clear("title1","feeStatusId")
					_that.$refs.autoform.changeEditor("title1","feeStatusId","type","labelbox")
				}
			},
		},
		methods: {
			clearFeeUser(){
				let _that = this
				_that.$refs.autoform.clear("title1","feeUserId")
				_that.$refs.autoform.clear("title1","feeInstId")
				_that.$refs.autoform.changeEditor("title1","feeInstId","data",configSelectData([],"id","instName"))
			},
			findInstByUserIdOrPostId(id,value){
				let _that = this
				_that.om.request(
					'orgInstPosUserOfficial/findInstByUserIdOrPostId',
					{
						userId: id
					}
				,'post').then(res=>{
					_that.$refs.autoform.changeEditor("title1",value,"data",configSelectData(res,"id","instName"))
					_that.$refs.autoform.initSelectIndex("title1",value)
				})
			},
			clearServiceUser(){
				let _that = this
				_that.$refs.autoform.clear("title1","serviceUserId")
				_that.$refs.autoform.clear("title1","serviceInstId")
				_that.$refs.autoform.changeEditor("title1","serviceInstId","data",configSelectData([],"id","instName"))
			},
			onselectRepairCompleteTime(value){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				if(_that.subEditorObj['title2']){
					let dataList = _that.subEditorObj['title2'].workList
					for(let index in dataList){
						dataList[index].repairCompleteTime = value
					}
					formdata.dataStr = JSON.stringify(dataList)
					if(_that.subEditorObj['title2']){
						_that.subEditorObj['title2'].workList = dataList
					}
					uni.setStorageSync('oldWorkList', JSON.stringify(dataList))
					_that.om.toast('子表数据已更新')
				}
			},
			onSubChange(editor){
				let _that = this.$refs.autoform
				let that = this
				if(editor.groupKey == 'title4' && editor.workList.length) {
					_that.formdata.feeAmount = this._.sum(editor.workList.map(e=>ptFloat(e.totalPrice)))
				}
				if(editor.groupKey == 'title2' && editor.workList.length) {
					let oldWorkListStr = uni.getStorageSync("oldWorkList");
					let oldWorkListArr = JSON.parse(oldWorkListStr)
					if(oldWorkListArr.length == editor.workList.length){
						for(let i=0; i<editor.workList.length; i++){
							if(editor.workList[i].repairCompleteTime != oldWorkListArr[i].repairCompleteTime){
								_that.formdata.repairCompleteTime = ""
							}
						}
					}else if(oldWorkListArr.length < editor.workList.length){
						for(let i=0; i<editor.workList.length;i++){
							if(_that.formdata.repairCompleteTime != editor.workList[i].repairCompleteTime){
								_that.formdata.repairCompleteTime = ""
							}
						}
					}else{
						
					}
					uni.setStorageSync('oldWorkList', JSON.stringify(editor.workList))
				}
			},
			onselectReceiptDate(data){
				let _that = this
				if (new Date(data).getTime() > new Date().getTime()) {
					errorModal(_that,'提示信息',"收款日期要≤当前日期，请重新选择！",()=>{
						_that.$refs.autoform.clear("title1",'receiptDate')
					})
				}
			},
			onselectInvoiceDate(data){
				let _that = this
				if (new Date(data).getTime() > new Date().getTime()) {
					errorModal(_that,'提示信息',"开票日期要≤当前日期，请重新选择！",()=>{
						_that.$refs.autoform.clear("title1",'invoiceDate')
					})
				}
			},
			onselectRepairCompleteDate(data){
				let _that = this
				if (new Date(data).getTime() > new Date().getTime()) {
					errorModal(_that,'提示信息',"维修完成日期要≤当前日期，请重新选择！",()=>{
						_that.$refs.autoform.clear("title1",'repairCompleteDate')
					})
				}
			},
			getWorkParam(){
				let _that = this
				return {
					repairCompleteTime:_that.$refs.autoform.formdata.repairCompleteTime,
				}
			},
			initLoad(options) {
				let _that = this;
				var fileId = options.fileId
				let ajaxArr = [
					zposUrl(options.code), //制表岗位
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'283',
							categoryId:'6431'
						}
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8826'
						}
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8831'
						}
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8900'
						}
					},{
						url:'common/getMenu',
						param:{
							formCode:options.code
						},
					}
				]
				if(fileId){
					ajaxArr.push({
						url:'afterSalesDispatch/getValue',
						param:{
							fileId:fileId
						}
					})
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					changeEditor("topinfo",'zinstId',{
						defaultValue:_that.salaryInstId,
						defaultName:_that.salaryInstName
					},null,mainData)
					changeEditor("title1",'serviceTypeId', 'data', configSelectData(res[2], 'id', 'text'), mainData);
					changeEditor("title1",'serviceNatureId', 'data', configSelectData(res[3], 'id', 'text'), mainData);
					changeEditor("title1",'feeStatusCode', 'data', configSelectData(res[1], 'code', 'text'), mainData);
					changeEditor("title1",'feeStatusId', 'data', configSelectData(res[4], 'code', 'text'), mainData);
					changeEditor("title1",'dispatchTime', 'noInitDate',true, mainData);
					changeEditor("title1",'repairCompleteTime', 'noInitDate',true, mainData);
					_that.menuList =  res[5].value
					if (_that.subEditorObj['title2']) {
						changeEditor('title2', 'productStr', {
							getWorkParam:'getWorkParam',
							titleTemplate: '产品名称：<%= newProductName || "无" %>',
							subtitle2Template: '故障原因：<%= faultCauseName  || "无" %>'
						}, null, mainData);
					}
					if (_that.subEditorObj['title3']) {
						changeEditor('title3', 'repairStr', {
							titleTemplate: '物料名称：<%= newProductName || "无" %>',
						}, null, mainData);
					}
					if (_that.subEditorObj['title4']) {
						changeEditor('title4', 'costStr', {
							titleTemplate: '维修费用项目：<%= repairCostItemsName || "无" %>',
							subtitle2Template: '金额：<%= totalPrice || "无" %>'
						}, null, mainData);
					}
				
					changeEditor("title1","serviceUserId",{
						"link":'../../public/searchUser/searchUser',
						"linkParam":{
							other:JSON.stringify({
							}),
							isSingle:true,
							isUserPos:true,
							isNew:true,
							cachename:_that.serviceUserIdCache
						}
					},null,mainData)
					changeEditor("title1","feeUserId",{
						"link":'../../public/searchUser/searchUser',
						"linkParam":{
							other:JSON.stringify({
							}),
							isSingle:true,
							isUserPos:true,
							isNew:true,
							cachename:_that.feeUserIdCache
						}
					},null,mainData)

						if(fileId){
							let fieldArr = getFormFields(mainData)
							fieldArr.push('id')
							for(let index in res[6].value){
								if(fieldArr.includes(index)){
									_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[6].value[index])
									_that.$set(_that.formdata,index,res[6].value[index])
								}
							}
							uni.setStorageSync('oldWorkList', JSON.stringify(res[6].value.productList))
							let dataList = _that._.cloneDeep(res[6].value.productList)
							_that.subEditorObj['title2'].workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,'productStr',JSON.stringify(dataList))
							_that.$set(_that.formdata,'productStr',JSON.stringify(dataList))
							delete res[6].value.productList
							
							let dataList2 = _that._.cloneDeep(res[6].value.repairList)
							_that.subEditorObj['title3'].workList = dataList2
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,'repairStr',JSON.stringify(dataList2))
							_that.$set(_that.formdata,'repairStr',JSON.stringify(dataList2))
							delete res[6].value.repairList
							
							let dataList3 = _that._.cloneDeep(res[6].value.costList)
							_that.subEditorObj['title4'].workList = dataList3
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,'costStr',JSON.stringify(dataList3))
							_that.$set(_that.formdata,'costStr',JSON.stringify(dataList3))
							delete res[6].value.costList
							
							changeEditor("title1","serviceUserId",{
								link:'../../public/pageSearch/pageSearch',
								"linkParam":{
									other:JSON.stringify({
										firstUserId:res[6].value.serviceUserId
									}),
									url:'temployee/getStaffCombogrid',
									namefield:'userPosInstName',
									initload:true,
									searchfield:'q',
									cachename:_that.serviceUserIdCache
								}
							},null,mainData)
							// _that.om.request('orgInstPosUserOfficial/findUserList', {
							// 	instId: res[6].value.feeInstId
							// }).then(res => {
							// 	changeEditor("title1",'serviceUserId', 'data', configSelectData(res, 'id', 'username'), mainData);
							// 	_that.$refs.autoform.initSelectIndex("title1","serviceUserId")
							// });
							_that.om.request(
								'orgInstPosUserOfficial/findInstByUserIdOrPostId',
								{
									userId: res[6].value.serviceUserId
								}
							,'post').then(res=>{
								_that.$refs.autoform.changeEditor("title1","serviceInstId","data",configSelectData(res,"id","instName"))
								_that.$refs.autoform.initSelectIndex("title1","serviceInstId")
							})
							
							if(_that.formdata.feeUserId){
								_that.findInstByUserIdOrPostId(_that.formdata.feeUserId,'feeInstId')
							}

						}
					_that.$nextTick(function(){
						if(_that.$refs.autoform){
							_that.$refs.autoform.initSelectIndex("title1","serviceTypeId")
							_that.$refs.autoform.initSelectIndex("title1","serviceNatureId")
							_that.$refs.autoform.initSelectIndex("title1","feeStatusCode")
							_that.$refs.autoform.initSelectIndex("title1","feeStatusId")
						}
					})
				}, options)
			},
			formSubmit() {
				let _that = this
				if(_that.subEditorObj["title2"]){
					let dataList = JSON.parse(_that.formdata.productStr)
					 for(let index in dataList){
						 if(!dataList[index].fileList){
							 delete dataList[index].fileList
						 }
					 }
					 _that.formdata.productStr = JSON.stringify(dataList)
				}
				if(this.checkedit) {
					_that.om.formSave('commonForm/doCheckOrApproveUpdate', _that.formdata, _that)
				} else if(this.edit){
					_that.om.formSave("afterSalesDispatch/doUpdate",_that.formdata,_that)
				} else {
					_that.om.formSave("afterSalesDispatch/doAdd",_that.formdata,_that)
				}
			}
		},
		onLoad(options) {
			this.initLoad(options)
			let a = [];
			uni.setStorageSync('oldWorkList', JSON.stringify(a))
		},
		onShow() {
			let _that = this;
			if (_that.$refs.autoform) {
				for (let fieldId in _that.subEditorObj) {
					let editor = _that.subEditorObj[fieldId];
					uni.getStorage({
						key: getWorkCacheKey(fieldId),
						success: function(res) {
							editor.workList = res.data;
							_that.onSubChange(editor)
							uni.removeStorage({
								key: getWorkCacheKey(fieldId)
							});
						}
					});
				}
			}
			uni.getStorage({
				key:_that.communicateUserIdCache,
				success:(res)=>{
					if(res.data){
						let d = res.data[0]
						let formdata = _that.$refs.autoform.formdata
						formdata.communicateUserId = d.id
						formdata.communicateUserName = d.username
						formdata.communicateInstId = d.posInfos[0].instId
						formdata.communicateInstName = d.posInfos[0].instName
						uni.removeStorage({
							key:_that.communicateUserIdCache
						})
					}
				}
			})
			uni.getStorage({
				key:_that.serviceUserIdCache,
				success:(res)=>{
					if(res.data){
						let d = res.data[0]
						let formdata = _that.$refs.autoform.formdata
						formdata.serviceUserId = d.id
						formdata.serviceUserName = d.username
						formdata.serviceInstId = d.instId
						formdata.serviceInstName = d.instName
						_that.findInstByUserIdOrPostId(d.id,'serviceInstId')
						uni.removeStorage({
							key:_that.serviceUserIdCache
						})
					}
				}
			})
			uni.getStorage({
				key:_that.feeUserIdCache,
				success:(res)=>{
					if(res.data){
						let d = res.data[0]
						let formdata = _that.$refs.autoform.formdata
						formdata.feeUserId = d.id
						formdata.feeUserName = d.username
						formdata.feeInstId = d.instId
						formdata.feeInstName = d.instName
						_that.findInstByUserIdOrPostId(d.id,'feeInstId')
						uni.removeStorage({
							key:_that.feeUserIdCache
						})
					}
				}
			})
			try {
				const value = uni.getStorageSync('chooseData');
				if (value) {
					let obj = {}
					let arr= []
					let name = ''
					let codes = []
					let sourceFormId = ''
					let formdata = _that.$refs.autoform.formdata
					if(value[0].busCode == 'AFT0203'){
						formdata.repairReportUserId = value[0].zuserId
						formdata.repairReportUserName = value[0].zuserName
						formdata.repairReportInstId = value[0].zinstId
						formdata.repairReportInstName = value[0].zinstName
					}else{
						formdata.repairReportUserId = value[0].repairReportUserId
						formdata.repairReportUserName = value[0].repairReportUserName
						formdata.repairReportInstId = value[0].repairReportInstId
						formdata.repairReportInstName = value[0].repairReportInstName
						formdata.assignTime = value[0].ztime
					}
					formdata.repairReportTime = value[0].ztime
					formdata.businessOwnerId = value[0].businessOwnerId
					formdata.businessOwnerName = value[0].businessOwnerName
					formdata.businessInstId = value[0].businessInstId
					formdata.businessInstName = value[0].businessInstName
					formdata.askTypeId = value[0].askTypeId
					formdata.askTypeName = value[0].askTypeName
					formdata.customerId = value[0].customerId
					formdata.customerCode = value[0].customerCode
					formdata.customerName = value[0].customerName
					formdata.customerContactId = value[0].customerContactId
					formdata.customerContactName = value[0].customerContactName
					formdata.customerContactPhone = value[0].customerContactPhone
					formdata.useCompany = value[0].useCompany
					formdata.useCompanyContact = value[0].useCompanyContact
					formdata.useCompanyContactPhone = value[0].useCompanyContactPhone
					formdata.locationId = value[0].locationId
					formdata.locationName = value[0].locationName
					formdata.userCompanyAddress = value[0].userCompanyAddress
					formdata.askDesperation = value[0].askDesperation
					formdata.expectFinishDate = value[0].expectFinishDate
					//沟通
					formdata.communicateUserId = value[0].communicateUserId
					formdata.communicateUserName = value[0].communicateUserName
					formdata.communicateResultId = value[0].communicateResultId
					formdata.communicateResultName = value[0].communicateResultName
					formdata.lateServiceTypeId = value[0].lateServiceTypeId
					formdata.lateServiceTypeName = value[0].lateServiceTypeName
					formdata.requiredCompleteDate = value[0].requiredCompleteDate
					formdata.communicateInstId = value[0].communicateInstId
					formdata.communicateInstName = value[0].communicateInstName
					formdata.communicateWayId = value[0].communicateWayId
					formdata.communicateWayName = value[0].communicateWayName
					formdata.communicateDate = value[0].communicateTime
					formdata.communicateRemark = value[0].communicateRemark
					formdata.cost = value[0].cost
					formdata.costDescription = value[0].costDescription
					for(let item of value){
						name = item.busName
						sourceFormId = item.id 
						codes.push(item.code)
						for(let subItem of item.subData){
							_that.$set(subItem,'faultCauseName','')
							arr.push(subItem)
						}
					}
					formdata.sourceFormCode = codes.map(e=> e).join(',')
					formdata.sourceFormName = name
					formdata.sourceFormId = sourceFormId
					if(_that.subEditorObj["title2"]){
						_that.subEditorObj["title2"].workList = arr
					}
					uni.removeStorageSync('chooseData')
				}
			} catch (e) {
				// error
			}
		}
	}
</script>

<style></style>
